/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.session;

import com.velocityme.entity.Anchor;
import com.velocityme.entity.ChangeDelta;
import com.velocityme.enums.ChangeDeltaItemType;
import com.velocityme.enums.ChangeDeltaType;
import com.velocityme.enums.Permission;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author rcrida
 */
@Stateless
public class AnchorBean implements AnchorLocal {
    @EJB
    private TaskLocal taskBean;

    @PersistenceContext
    private EntityManager em;

    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    public Anchor findAnchor(KeyLocal key, Long anchorId) {
        Anchor anchor = em.find(Anchor.class, anchorId);
        key.assertHasPermission(anchor, Permission.NODE_VIEW);
        return anchor;
    }

    public Anchor createAnchor(KeyLocal key, Anchor anchor, boolean interested) {
        key.assertHasPermission(anchor.getParentNode(), Permission.ANCHOR_CREATE);
        anchor.setStopDate(anchor.getStartDate());
        ChangeDelta changeDelta = anchor.addChangeDelta(ChangeDeltaType.CREATE, key.getUser());
        changeDelta.addItem(ChangeDeltaItemType.DATE, formatter.format(anchor.getStartDate()));
        taskBean.logCreate(anchor, changeDelta, interested);
        em.persist(anchor);
        em.persist(changeDelta);
        return anchor;
    }

    public void editAnchor(KeyLocal key, Anchor anchor) {
        Anchor current = em.find(Anchor.class, anchor.getId());
        key.assertHasPermission(anchor, Permission.ANCHOR_EDIT);
        ChangeDelta changeDelta = anchor.addChangeDelta(ChangeDeltaType.EDIT, key.getUser());
        if (!anchor.getStartDate().equals(current.getStartDate())) {
            changeDelta.addItem(ChangeDeltaItemType.DATE, formatter.format(anchor.getStartDate()));
        }
        taskBean.logEdit(anchor, current, changeDelta);
        em.merge(anchor);
        em.persist(changeDelta);
    }
 
}
